package com.cxb.java;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

/**
 * @Classname NotReentrantSemaphoreMutex
 * @Date 2023/4/1 14:42
 * @Created by Administrator
 * @Description TODO
 */
public class NotReentrantSemaphoreMutex {
    public static final String ZOOKEEPER_STRING = "127.0.0.1:2181";

    public static CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(ZOOKEEPER_STRING, new ExponentialBackoffRetry(1000, 3));

    public NotReentrantSemaphoreMutex() {
        curatorFramework.start();
    }

    public void deduct() {
        InterProcessSemaphoreMutex mutex = new InterProcessSemaphoreMutex(curatorFramework, "/curator/lock");
        try {
            boolean flag = mutex.acquire(3, TimeUnit.SECONDS);
            if (flag) {
                // 处理业务
                // 例如查询库存 扣减库存
                Thread.sleep(1000);
                System.out.println("执行业务逻辑");
            } else {
                System.out.println("未获取到锁");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                mutex.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 该锁是不可重入锁
     * @param args
     */
    public static void main(String[] args) {
        InterProcessSemaphoreMutex mutex = new InterProcessSemaphoreMutex(curatorFramework, "/HRHK_ZT/ST");
        try {
            boolean flag = mutex.acquire(3, TimeUnit.SECONDS);
            if (flag) {
                NotReentrantSemaphoreMutex notReentrantSemaphoreMutex = new NotReentrantSemaphoreMutex();
                notReentrantSemaphoreMutex.deduct();
            } else {
                System.out.println("main获取锁失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                mutex.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
